package com.nce.protocol.rtp;

public class RTPHeader {
	
	private static final int DEFAULT_VERSION = 2;
	private static final int PAYLOAD_TYPE_UNKNOWN = -1;
	
	
	public byte[] dataExtension = null; /* including the initial 4 bytes */
	public int version = DEFAULT_VERSION;
	public boolean padding = false;
	public boolean extension = false;
	public int cc = 0;
	public boolean marker = false;
	
	public int payloadType = PAYLOAD_TYPE_UNKNOWN;
	
	public int sequenceNumber = 0;
	public int timestamp = 0;
	public int ssrc = 0;
	public int [] csrc = null;
	public int headerExtensionSizeInBytes = 0; /* excluding the initial 4 bytes */
	
	public int totalHeaderSize = 0;
	
	public RTPHeader(byte[] packet) throws NotAValidHeaderException
	{
		if (packet == null || packet.length < 12)
			throw new NotAValidHeaderException();
		
		version = (packet[0] & 0x03 );
		padding = ((packet[0] & 0x04 ) != 0);
		extension = ((packet[0] & 0x08) != 0);
		cc = ((packet[0] & 0x30) >> 4);
		marker = ((packet[1] & 0x01 ) != 0);
		payloadType = ((packet[1]) & 0x7A >> 1);
		sequenceNumber = (((packet[2] & 0xFF) << 8) | (packet[3] & 0xFF) );
		timestamp = readInt(packet, 4);
		ssrc = readInt(packet, 8);
		int offset = 12;
		if (cc > 0)
		{
			csrc = new int[cc];
			for (int i = 0; i < cc; i++)
			{
				csrc[i] = readInt(packet, offset);
				offset+=4;
			}
		}
		if (extension)
		{
			int exsize = (((packet[offset] & 0xFF) << 8) | (packet[offset+1] & 0xFF) );
			headerExtensionSizeInBytes = exsize * 4;
			dataExtension = new byte[headerExtensionSizeInBytes + 4];
			System.arraycopy(packet, offset, dataExtension, 0, dataExtension.length);
		}
		totalHeaderSize = 12 + cc + headerExtensionSizeInBytes;
		//int headerSize = 12 + cc + headerExtensionSizeInBytes;
		//data = new byte[headerSize];
		//System.arraycopy(packet, 0, data, 0, headerSize);
		
	}
	
	private int readInt(byte [] buff, int offset)
	{
		return ((buff[offset] & 0xFF) << 24 ) |
					  ((buff[offset+1] & 0xFF) << 16 ) |
					  ((buff[offset+2] & 0xFF) << 8 ) |
					  ((buff[offset+3] & 0xFF) );
	}
	
}
